package com.ghostwan.androears;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import com.ghostwan.androears.customObject.Song;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MusicPlayer
{

	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */

	protected final static String TAG = "MusicPlayer";
	public static final int DELAY = 100;
	public int mPercent;
	public MusicPlayerInterface mPlayerService;
	public View mView;
	public int mCurrentPosition;
	public boolean mIsSongPLay;
	public boolean mIsSongLoad;
	private TextView mElaspedTimeText;
	private SeekBar mSeekBar;
	private AndroEars mAndroEars;
	private ConnectivityManager mConnectivityManager;
	final public Handler mHandler = new Handler();
	public Runnable mUpdateTimeTask = new Runnable()
	{
		public void run()
		{
			if (mIsSongPLay && mAndroEars.mCurrentView == AndroEars.PLAYER_VIEW)
			{
				try
				{
					mSeekBar.setProgress((int) mPlayerService.getElapsedTime());
				}
				catch (RemoteException e)
				{
					Log.e(TAG, e.getMessage());
				}
				/*
				 * mHandler.postAtTime(this, start + (((minutes * 60) + seconds
				 * + 1) * 1000));
				 */
				mHandler.postDelayed(mUpdateTimeTask, DELAY);
			}

		}
	};

	public MusicPlayer(final AndroEars androearsMain, View view)
	{
		super();
		mAndroEars = androearsMain;
		mPlayerService = mAndroEars.mPlayerService;
		mView = view;
		mCurrentPosition = 0;
		mElaspedTimeText = ((TextView) mView.findViewById(R.id.elapsedTime));
		mSeekBar = ((SeekBar) mView.findViewById(R.id.SeekBar01));
		mIsSongPLay = false;
		mIsSongLoad = false;
		mConnectivityManager = (ConnectivityManager) mAndroEars
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		
		((ImageButton) mView.findViewById(R.id.playButton))
				.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v)
					{

						try
						{
							if (mIsSongPLay)
							{
								pause();
							}
							else
							{
								if (!mIsSongLoad)
									loadSongList(mCurrentPosition);
								else
									play();
							}

						}
						catch (Exception e)
						{
							Log.e(TAG, "error play: " + e.getMessage(), e);
						}

					}
				});
		((ImageButton) mView.findViewById(R.id.nextButton))
				.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v)
					{

						next();

					}
				});
		((ImageButton) mView.findViewById(R.id.previousButton))
				.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v)
					{

						previous();

					}
				});

		/*((ImageButton) mView.findViewById(R.id.stopButton))
				.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v)
					{

						try
						{
							stop();
						}
						catch (RemoteException e)
						{
							// TODO Auto-generated catch block
							Log.e(TAG, e.getMessage());
						}

					}
				});*/
		((ImageButton) mView.findViewById(R.id.listButton))
				.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v)
					{

						androearsMain.setContentView(androearsMain.mMainView);
						androearsMain.displayArtistList();

					}
				});

		((ImageButton) mView.findViewById(R.id.playlistButton))
				.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v)
					{

						androearsMain.setContentView(R.layout.playlist);
						androearsMain.displayPlayList();

					}
				});

		mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
		{

			private boolean isSeeking;

			@Override
			public void onStopTrackingTouch(SeekBar seekBar)
			{
				try
				{
					isSeeking = false;
					mPlayerService.seekTo(seekBar.getProgress());
					// mPlayerService.play();
				}
				catch (RemoteException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar)
			{
				try
				{
					isSeeking = true;
					mPlayerService.seekTo(seekBar.getProgress());
					// mPlayerService.pause();
				}
				catch (RemoteException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
			{
				try
				{
					if (isSeeking)
					{
						mPlayerService.seekTo(seekBar.getProgress());
					}
					long millis = progress;
					long seconds = (millis / 1000) % 60;
					long minutes = (millis / 60000);
					NumberFormat formatter = new DecimalFormat("00");
					mElaspedTimeText.setText(formatter.format(minutes) + ":"
							+ formatter.format(seconds));
				}
				catch (RemoteException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	public void next()
	{
		try
		{
			mPlayerService.skipForward();
			mCurrentPosition = mPlayerService.getCurrentPosition();
			prepareSongPlaying(mPlayerService.getCurrentSong());
			play();

		}
		catch (Exception e)
		{
			Log.e(TAG, "error next: " + e.getMessage(), e);
		}
	}

	public void previous()
	{
		try
		{
			mPlayerService.skipBack();
			mCurrentPosition = mPlayerService.getCurrentPosition();
			prepareSongPlaying(mPlayerService.getCurrentSong());
			play();

		}
		catch (Exception e)
		{
			Log.e(TAG, "error previous: " + e.getMessage(), e);
		}
	}

	public void play() throws RemoteException
	{
		((ImageButton) mView.findViewById(R.id.playButton)).setImageResource(R.drawable.selector_pause);
		mIsSongPLay = true;
		mPlayerService.play();
		mHandler.postDelayed(mUpdateTimeTask, 0);
		if (!mIsSongLoad)
		{
			prepareSongPlaying(mPlayerService.getCurrentSong());
			mIsSongLoad = true;
		}
	}

	public void pause() throws RemoteException
	{
		((ImageButton) mView.findViewById(R.id.playButton)).setImageResource(R.drawable.selector_play);
		mIsSongPLay = false;
		mPlayerService.pause();
	}

	public void stop() throws RemoteException
	{
		((ImageButton) mView.findViewById(R.id.playButton)).setImageResource(R.drawable.selector_play);
		mPlayerService.stop();
		mIsSongLoad = false;
		mIsSongPLay = false;
		prepareSongPlaying(mPlayerService.getCurrentSong());
	}

	public void loadSongList(int position)
	{
		try
		{

			mCurrentPosition = position;
			mPlayerService.playList(mCurrentPosition);
			prepareSongPlaying(mPlayerService.getCurrentSong());
			// play();
		}
		catch (Exception e)
		{
			Log.e(TAG, "error loadSong: " + e.getMessage(), e);
		}

		mIsSongLoad = true;
	}

	public void prepareSongPlaying(Song song)
	{
		((TextView) mView.findViewById(R.id.songName)).setText(song.mSongName);
		((TextView) mView.findViewById(R.id.albumName)).setText(song.mAlbumName);
		((TextView) mView.findViewById(R.id.artistName)).setText(song.mArtistName);
		mHandler.postDelayed(mUpdateTimeTask, DELAY);
		mSeekBar.setProgress(0);
		mElaspedTimeText.setText("00:00");
		mSeekBar.setMax((int) song.mDuration);
		if (song.mSongCover != null)
		{
			((ImageView) mView.findViewById(R.id.coverView))
					.setImageURI(Uri.parse(song.mSongCover));
			Log.d(TAG, "debug cover path: " + song.mSongCover);
		}
		else
			((ImageView) mView.findViewById(R.id.coverView)).setImageResource(R.drawable.note);

		TextView songDurationText = ((TextView) mView.findViewById(R.id.duration));
		long z = song.mDuration;
		long s = (z / 1000) % 60;
		long m = (z / 60000);
		NumberFormat formatter = new DecimalFormat("00");
		songDurationText.setText(formatter.format(m) + ":" + formatter.format(s));

	}
	

	public String convertStreamToString(InputStream is) throws IOException {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        if (is != null) {
            StringBuilder sb = new StringBuilder();
            String line;

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                is.close();
            }
            return sb.toString();
        } else {        
            return "";
        }
    }
	
	public String getLyrics(Song song)
	{
		String lyrics = "";
		/*if (mConnectivityManager.getNetworkInfo(0).isConnectedOrConnecting())
		{
			/*
			 * try {
			 * 
			 * String query = "action=lyrcis&fmt=xml&func=getSong"
			 * +"&artist="+song.mArtistName.replace(" ", "%20")
			 * +"&song="+song.mSongName.replace(" ", "%20"); URL url = new
			 * URL("http://lyrics.wikia.com/api.php?"+query); // Read all the
			 * text returned by the server BufferedReader in = new
			 * BufferedReader(new InputStreamReader(url.openStream())); String
			 * line; while ((line = in.readLine()) != null) { lyrics += line; }
			 * in.close(); } catch (Exception e) { Log.e(TAG, e.getMessage()); }
			 
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			HttpClient httpClient = new DefaultHttpClient();

			StringBuilder uriBuilder = new StringBuilder("http://lyrics.wikia.com/api.php?");
			uriBuilder.append("action=lyrics&fmt=text&func=getSong");
			uriBuilder.append("&song=" + song.mSongName.replace(" ", "%20"));
			uriBuilder.append("&artist=" + song.mArtistName.replace(" ", "%20"));
			
			HttpGet request = new HttpGet(uriBuilder.toString());
			HttpResponse response;
			try
			{
				response = httpClient.execute(request);
				int status = response.getStatusLine().getStatusCode();
				// we assume that the response body contains the error message
				if (status != HttpStatus.SC_OK) {
					ByteArrayOutputStream ostream = new ByteArrayOutputStream();
					response.getEntity().writeTo(ostream);
					Log.d(TAG, ostream.toString());
				} else {
					InputStream content = response.getEntity().getContent();
					lyrics = convertStreamToString(content);
					
					DocumentBuilder builder = factory.newDocumentBuilder();
		            Document dom = builder.parse(content);
		            Element root = dom.getDocumentElement();
		            NodeList items = root.getElementsByTagName("result");
		            if(items.getLength() != 1) 
		            	return null;
		           // NamedNodeMap  attributes = items.item(0).getAttributes();
					Log.e(TAG, lyrics);
					content.close(); // this will also close the connection
				}
			}
			catch (ClientProtocolException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (SAXException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (ParserConfigurationException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}*/
		return lyrics;
	}

}
